#include "sendidcommand.h"

#include <sstream>
using  namespace std;

#include <Poco/DOM/Document.h>
#include <Poco/DOM/Element.h>
#include <Poco/DOM/DOMWriter.h>
#include <Poco/DOM/DOMParser.h>
#include <Poco/DOM/NodeList.h>
using Poco::XML::Document;
using Poco::XML::Element;
using Poco::XML::DOMWriter;
using Poco::XML::DOMParser;
using Poco::XML::NodeList;

namespace Commands {

	string const SendIdCommand::NAME = "SendId";

	SendIdCommand::SendIdCommand(id_type id, NodeData* data)
		: NodeCommand(data, true)
		  , _id(id)
	{
	}

	void SendIdCommand::execute()
	{
		cout << "SendIdCommand :: Setting Prev ID to " << _id << endl;
		node()->setPrevId(_id);
		ostringstream ss; ss << nodeId();
		setResult(ss.str());
	}

	string SendIdCommand::name()
	{
		return string(SendIdCommand::NAME);
	}

	string SendIdCommand::repr()
	{
		ostringstream out;
		DOMWriter w;
		w.writeNode(out, toXML());
		return out.str();
	}

	Document* SendIdCommand::toXML(Document*)
	{
		Document* doc = new Document();

		Element* prev = doc->createElement("prev-node");
		ostringstream ss; ss << _id;
		prev->setAttribute("id", ss.str());
		doc->appendChild(prev);

		return NodeCommand::toXML(doc);
	}

	CommandCreator SendIdCommand::creator()
	{
		return &SendIdCommand::makeCommand;
	}

	Command* SendIdCommand::makeCommand(string r, void* d)
	{
		NodeData* ndata = (NodeData*) d;
		DOMParser parser;
		Document* doc = parser.parseString(r);

		id_type pid;
		istringstream(((Element*)(doc->getElementsByTagName("prev-node")->item(0)))->getAttribute("id")) >> pid;

		return new SendIdCommand(pid, ndata);
	}
}
